﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Controller.Enum;
using Model;

namespace SalePriceSystem.Page
{
    public partial class ImportNDPrice : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void bthUploadExcel_Click(object sender, EventArgs e)
        {
            if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentType.Contains("spreadsheetml"))
            {
                string pathsave = "/Upload/" + DateTime.Today.ToString("dd-MM-yyyy") + "/";
                string folderpath = System.Web.HttpContext.Current.Server.MapPath(pathsave);
                if (!System.IO.Directory.Exists(folderpath))
                {
                    System.IO.Directory.CreateDirectory(folderpath);
                }
                FileUpload1.SaveAs(folderpath + FileUpload1.FileName);
                try
                {
                    List<tblNDPrice> ps = new List<tblNDPrice>();
                    tblNDPrice p = new tblNDPrice();
                    p.Createby = Controller.AD.LdapAuthentication.GetCurrentUser();
                    p.Created = DateTime.Now;
                    p.ValidON = DateTime.Now;
                    p.ValidTO = Convert.ToDateTime("12/31/" + DateTime.Now.Year);
                    p.remark = "load data on " + DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
                    ps.Add(p);
                    int round = Controller.Helper.NDPrice.DocumentAction(ps, EnumAction.Insert);
                    List<tblNDPriceDetail> docs = Controller.Helper.ExcelHelper.GetExcelDataToNdData(folderpath + FileUpload1.FileName, round, true);
                    int saveNDPriceDetail = Controller.Helper.NDPrice.NdPriceDetailAction(docs, EnumAction.Insert);
                    LiteralReport.Text = string.Format("Import success with {0} record", saveNDPriceDetail);
                    btnCloseButton.Visible = true;
                    bthUploadExcel.Visible = false;
                }
                catch (Exception)
                {

                    LiteralReport.Text = string.Format("Import not success please contact your administrator");
                }
                
            }
            else
            {
                LiteralReport.Text = string.Format("Please upload the correct file");
            }
        }
    }
}